<template>
  <div class="container">
  <el-card>
    <div class="set-container">
      <div class="select-container">
        <el-form ref="selectForm" :inline="true" :model="selectForm" class="select-form">
          <el-form-item prop="username" label="员工姓名:">
            <el-input v-model="selectForm.username" placeholder="请输入要查找的用户姓名"></el-input>
          </el-form-item>
          <el-form-item prop="date" label="注册时间:">
            <el-date-picker
                v-model="selectForm.date"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitSelect(1)">查询</el-button>
            <el-button type="info" @click="resetSelect">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="button-container">
        <el-button type="success" @click="openAddEmpDialog">新增员工</el-button>
        <el-button type="warning">批量注销</el-button>
        <el-button type="info">导出表格</el-button>
      </div>
    </div>
    <el-divider><h3 style="text-align: center">员工信息表格</h3></el-divider>
    <div class="table-container">
      <el-table
          v-if="tableData.length > 0"
          :data="tableData"
          @selection-change="handleSelectionChange"
          border
          stripe
          style="width: 100%">
        <el-table-column
            type="selection"
            width="40">
        </el-table-column>
        <el-table-column prop="avatarUrl" label="头像" width="55">
          <template slot-scope="scope">
            <div class="avatar-center">
              <el-avatar
                  shape="square"
                  :size="35"
                  :src="scope.row.avatarUrl"
              >
                <img
                    src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
                    alt="头像"
                />
              </el-avatar>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名"
            width="80">
        </el-table-column>
        <el-table-column
            prop="username"
            label="用户名"
            width="180">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="手机号"
            width="200">
        </el-table-column>
        <el-table-column
            prop="sex"
            label="性别"
            width="50">
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            {{ formatCreateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createUser" label="创建者" width="100">
        </el-table-column>
        <el-table-column prop="authority" label="权限" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.authority === 2" type="success" effect="dark">管理员</el-tag>
            <el-tag v-else-if="scope.row.authority === 1" effect="dark">普通员工</el-tag>
            <el-tag v-else-if="scope.row.authority === 0" type="warning" effect="dark">注销员工</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.status === 0" type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="270">
          <template slot-scope="scope">
            <el-button-group>
              <el-button type="primary" icon="el-icon-edit" size="mini" plain @click="openEditEmpDialog(scope.row.id)" >编辑</el-button>
              <el-button  v-if="scope.row.authority===1||scope.row.authority===2" type="warning" icon="el-icon-user" size="mini" plain @click="logout(scope.row.id,0)" >注销</el-button>
              <el-button  v-else icon="el-icon-user" size="mini" plain @click="logout(scope.row.id,1)">激活</el-button>
              <el-button  v-if="scope.row.status===1" type="danger" icon="el-icon-lock" size="mini"  plain @click="startOrStop(scope.row.id,0)">停用</el-button>
              <el-button  v-else type="success" icon="el-icon-unlock" size="mini" plain @click="startOrStop(scope.row.id,1)">启用</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <el-empty :image-size=350 v-else description="暂无数据"></el-empty>
    </div>
    <el-divider></el-divider>
    <div class="page">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="selectForm.page"
          :page-sizes="[5, 7, 10, 20, 50]"
          :page-size="selectForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </el-card>
    <el-dialog
        title="新增员工"
        :visible.sync="addEmpDialog"
        width="30%"
        top="5vh"
       >

      <el-form
          :model="addEmpForm"
          :rules="addEmpRules"
          ref="addEmpForm"
          label-width="100px"
          class="addEmpForm"
      >
        <el-form-item prop="avatarUrl" label="头像">
          <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadAvatar"
          >
            <img v-if="addEmpForm.avatarUrl" :src="addEmpForm.avatarUrl" class="avatar" alt="头像">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="name" label="姓名">
          <el-input
              v-model="addEmpForm.name"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input
              v-model="addEmpForm.username"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input
              v-model="addEmpForm.phone"
              minlength="11"
              maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别">
            <el-radio v-model="addEmpForm.sex" label="男">男</el-radio>
            <el-radio v-model="addEmpForm.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item prop="idNumber" label="身份证号">
          <el-input
            v-model="addEmpForm.idNumber"
            maxlength="18"
            show-word-limit
            ></el-input>
          </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="submitAddEmpForm(addEmpForm)"
          >提交</el-button
          >
          <el-button @click="resetAddEmpForm"
          >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
        title="编辑员工"
        :visible.sync="editEmpDialog"
        width="30%"
        top="2vh"
    >
      <el-form  :model="editEmpForm"
                :rules="addEmpRules"
                ref="editEmpForm"
                label-width="100px"
                class="editEmpForm">
        <el-form-item prop="avatarUrl" label="头像">
          <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadEditAvatar"
          >
            <img v-if="editEmpForm.avatarUrl" :src="editEmpForm.avatarUrl" class="avatar" alt="头像">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="name" label="姓名">
          <el-input
              v-model="editEmpForm.name"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input
              v-model="editEmpForm.username"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input
              v-model="editEmpForm.phone"
              minlength="11"
              maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-radio v-model="editEmpForm.sex" label="男">男</el-radio>
          <el-radio v-model="editEmpForm.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item prop="authority" label="权限">
          <el-select v-model="editEmpForm.authority" placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="idNumber" label="身份证号">
          <el-input
              v-model="editEmpForm.idNumber"
              maxlength="18"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="submitEditEmpForm(editEmpForm)"
          >提交</el-button
          >
          <el-button @click="resetEditEmpForm"
          >重置</el-button
          >
          <el-button type="danger" style="margin-left: 30%" @click="centerDialogVisible=true">重置密码</el-button>
        </el-form-item>
      </el-form>
      <el-divider><i class="el-icon-edit"></i></el-divider>
      <el-dialog
          title="确定重置该员工的密码？"
          :visible.sync="centerDialogVisible"
          width="30%"
          center
          append-to-body>
        <h3 style="text-align: center;color: red">这会使该员工的密码变为系统默认密码，且立即提交</h3>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="resetEmpPwd">确 定</el-button>
  </span>
      </el-dialog>
    </el-dialog>

  </div>
</template>


<script>
import axios from "@/api/axios";

export default {
  data(){
    return{
      selectForm:{
        username:"",
        date:"",
        pageSize:7,
        page:1
      },

      total:0,
      tableData: [],

      addEmpForm:{
        avatarUrl:"",
        name:"",
        username:"",
        phone:"",
        sex:"男",
        idNumber:"",
      },

      editEmpForm:{
        id:"",
        avatarUrl:"",
        name:"",
        username:"",
        phone:"",
        sex:"男",
        idNumber:"",
        authority:1,
      },

      addEmpDialog:false,
      editEmpDialog:false,
      centerDialogVisible:false,

      options: [{
        value: 0,
        label: '注销员工'
      }, {
        value: 1,
        label: '普通员工'
      }, {
        value: 2,
        label: '管理员'
      }],

      addEmpRules:{
        name: [
            { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 16,
            message: "长度在 2 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号码",
            trigger: "blur",
          },
          {
            min: 11,
            max: 11,
            message: "手机号码长度必须为11位",
            trigger: "blur",
          },
          {
            pattern: /^1\d{10}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
          {
            validator: this.noSpacesValidator,
            trigger: "blur",
          },
        ],
        idNumber: [
          {
            required: true,
            pattern: /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: "请输入正确的身份证号",
            trigger: "blur"
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ]
      }
    }
  },

  mounted() {
    this.submitSelect();
  },

  methods: {
    /**
     * 表格数据查询函数
     */
    submitSelect(flag) {
      this.$refs.selectForm.validate((valid) => {
        if (flag===1) {
          this.selectForm.page = 1;// 重新查询时，将页码置为第一页
        }
        if (valid) {
          const formData = {
            page: this.selectForm.page,
            pageSize: this.selectForm.pageSize,
            name: this.selectForm.username,
            begin: this.formatDate(this.selectForm.date[0]),
            end: this.formatDate(this.selectForm.date[1]),
          };

          axios.post("/admin/emp/list", formData).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
            }
          }).catch(error=> {
            // 处理请求错误
            console.log(error);
          });
        }else{
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 日期处理函数
     * @param date
     * @returns {null|string}
     */
    formatDate(date) {
      if (date instanceof Date) {
        // 返回格式化后的日期时间字符串（ISO 8601 UTC格式，不包含毫秒）
        return (
            date.toISOString().split("T")[0] +
            "T" +
            date.toISOString().split("T")[1].split(".")[0]
        );
      } else {
        // 如果日期为空或者不是Date对象，返回null或空字符串，或者根据你的需求返回其他默认值
        return null; // 或者 ""，取决于后端如何处理这种情况
      }
    },

    /**
     * 查询表单重置函数
     */
    resetSelect() {
      this.$refs.selectForm.resetFields(this.selectForm);
      this.$message.info("重置成功");
    },

    /**
     * 两个分页选项函数
     * @param val
     */
    handleSizeChange(val) {
      this.selectForm.pageSize = val;
      this.submitSelect();
    },
    handleCurrentChange(val) {
      this.selectForm.page=val;
      this.submitSelect();
    },

    /**
     * 给返回的时间格式化函数
     * @param {Array} createTime - 包含年、月、日、时、分、秒的数组
     * @returns {string}
     */
    formatCreateTime(createTime) {
      const [year, month, day, hour, minute = '00', second = '00'] = createTime;
      return `${year}-${this.padZero(month)}-${this.padZero(day)} ${this.padZero(hour)}:${this.padZero(minute)}:${this.padZero(second)}`;
    },

    /**
     * 将数字补零
     * @param {number|string} num
     * @returns {string}
     */
    padZero(num) {
      return num.toString().padStart(2, '0');
    },

    /**
     * 选择框
     */
    handleSelectionChange(val){
      console.log(val);
    },

    openAddEmpDialog(){
      this.addEmpDialog=true;
    },

    /*头像上传方法*/
    uploadAvatar(file) {
      axios.post("/admin/common/upload", file,{headers:{'Content-Type': 'multipart/form-data',}}).then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.addEmpForm.avatarUrl=response.data.data;
          this.$message.success("上传成功");
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    uploadEditAvatar(file) {
      axios.post("/admin/common/upload", file,{headers:{'Content-Type': 'multipart/form-data',}}).then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.editEmpForm.avatarUrl=response.data.data;
          this.$message.success("上传成功");
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    /**
     * 空格校验
     * @param rule
     * @param value
     * @param callback
     */
    noSpacesValidator(rule, value, callback) {
      if (value && typeof value === "string" && value.includes(" ")) {
        callback(new Error("不能包含空格"));
      } else {
        callback();
      }
    },

    /**
     * 重置添加员工
     */
    resetAddEmpForm(){
      this.$refs.addEmpForm.resetFields();
    },

    /**
     * 添加员工
     */
    submitAddEmpForm(){
      this.$refs["addEmpForm"].validate((valid) => {
        if (valid) {
          axios.post("/admin/emp/add", this.addEmpForm).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.$message.success("添加成功");
              this.addEmpDialog = false;
              this.submitSelect();//刷新页面
            }
          }).catch(error=> {
            // 处理请求错误
            console.log(error);
          });
        }else{
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 编辑员工
     */
    openEditEmpDialog(id){
      this.editEmpDialog=true;
      this.getEmpById(id);
    },

    /*信息回显*/
    getEmpById(id) {
      axios.get("/admin/emp/" + id).then(response => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        } else {
          this.editEmpForm = response.data.data;
        }
      }).catch(error => {
        console.log(error);
      })
    },

    /*重置表单*/
    resetEditEmpForm(){
      this.getEmpById(this.editEmpForm.id);
    },

    /*提交表单*/
    submitEditEmpForm(){
      this.$refs["editEmpForm"].validate((valid) => {
        if (valid) {
          axios.put("/admin/emp/update", this.editEmpForm).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.$message.success("修改成功");
              this.editEmpDialog = false;
              this.submitSelect();//刷新页面
            }
          }).catch(error=> {
            console.log(error);
          })
        }else {
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 重置密码
     */
    resetEmpPwd() {
      this.centerDialogVisible = false;
      axios.put("/admin/emp/resetPwd/" + this.editEmpForm.id).then(response => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        } else {
          this.$message.success("重置成功");
        }
      }).catch(error => {
        console.log(error);
      })
    },

    /**
     * 停用启用
     */
    startOrStop(id, status) {
      axios.put("/admin/emp/resetStatus/"+id+"/"+status).then(response => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        }else {
          this.submitSelect();//刷新页面
        }
      }).catch(error => {
        console.log(error);
      })
    },

    /**
     * 注销
     */
    logout(id,auth) {
      axios.put("/admin/emp/logout/" + id + "/" + auth).then(response => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        }else {
         this.submitSelect();//刷新页面
        }
      }).catch(error => {
        console.log(error);
      })
    }
  }
}
</script>

<style scoped>
/*表格顶部设置栏*/
.set-container{
  display: flex;
}

.button-container{
  margin-left: auto; /* 将按钮容器向右对齐 */
}

/*表格最小高度*/
.table-container{
  min-height: 60vh;
}

/*分页*/
.page{
  margin-top: 20px;
}
</style>